#这道题也是一道BFS搜索得题，相对复杂些，但是思想也是一样，队列保存状态，集合SET进行去重


from collections import deque
def bfs(juli):
    n = len(juli)
    a= [(0, 1), (0, -1), (1, 0), (-1, 0)]
    fw= [[False] * n for _ in range(n)]
    queue = deque()
    for i in range(n):
        for j in range(n):
            if juli[i][j] == 'A':
                start = (i, j)
            elif juli[i][j] == 'B':
                end=(i,j)
    queue.append((start, 0, juli[start[0]][start[1]]))
    while queue:
        (x, y), step, current_weizhi = queue.popleft()
        fw[x][y] = True
        for dx, dy in a:
            nx, ny = x + dx, y + dy
            if 0 <= nx < n and 0 <= ny < n and not fw[nx][ny]:
                next_energy = juli[nx][ny]
                if next_energy!= current_weizhi:
                    if (nx, ny) == end:
                        return step + 1
                    fw[nx][ny] = True
                    queue.append(((nx, ny), step + 1, next_energy))
    return -1
n= int(input())
juli= [input().split() for _ in range(n)]
print(bfs(juli))